'use strict';

angular.module('rest', [])
	.service('rest', function($http, md5,signature,apiUrl,javaUrl,decoJavaUrl,decoJavaUrlLsf) {
		this.send = function(methodId, data) {
			var norcData = signature.run(methodId, data);
			// 此处需要做跨域配置，先换jquery的$.ajax
			return $http.post(apiUrl, norcData)
		};

		/*
			rest.java({
				url: '/decorate-service/decorate/api/service/getCreditLine.json',
				data: {
					originalId: 'f3d4c3b68c7935fcb018b4fa0cabfb2d'
				},
				success: function (data) {
	
				}
			});

		*/
		this.java = function (opt) {
			if (!opt.url) {
				throw new Error("url 不能为空！");
			}
			var opturl = javaUrl + opt.url;

			$.ajax({
				url: opturl,
				data: opt.data,
				type: "post",
				success: opt.success,
				error: opt.error,
				complete: opt.complete
			})
		};
		this.deco = function (opt) {
			if (!opt.url) {
				throw new Error("url 不能为空！");
			}
			var opturl = decoJavaUrl + opt.url;

			$.ajax({
				url: opturl,
				data: opt.data,
				type: "post",
				success: opt.success,
				error: opt.error,
				complete: opt.complete
			})
		};
		this.decoJava = function (opt) {
			if (!opt.url) {
				throw new Error("url 不能为空！");
			}
			var opturl = decoJavaUrlLsf + opt.url;

			$.ajax({
				url: opturl,
				data: opt.data,
				type: opt.type,
				dataType: "json",
				beforeSend:opt.beforeSend,
				contentType: opt.contentType,
				success: opt.success,
				error: opt.error,
				complete: opt.complete
			})
		};
		this.post = function(opt) {
			// 换jquery，此处由$.ajax进行处理，封装url: url和type: post，以及数据签名
			if (opt.log) {
				console.log("==== signData ==== rest.post ====");
				console.log(signature.run(opt.methodId, opt.data));
			}

			if(!opt.methodId){
				throw new Error("methodId 不能为空！")
			}
			if(!opt.data){
				opt.data = {}
			}
			$.ajax({
				url: opt.url || apiUrl,
				data: signature.run(opt.methodId, opt.data),
				type: "post",
				success: opt.success,
				error: opt.error,
				complete: opt.complete
			})
		};

		this.get = function(opt){
			if(!opt.methodId){
				throw new Error("methodId 不能为空！")
			}
			if(!opt.data){
				opt.data = {}
			}
			$.ajax({
				url: opt.url || apiUrl,
				data: signature.run(opt.methodId, opt.data),
				type: "get",
				success: opt.success,
				error: opt.error,
				complete: opt.complete
			})
		}
	});
